package boc.sx.gateway.socket.server;

import boc.sx.gateway.socket.server.initializer.HttpServerInitializer;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class HttpServer implements Runnable{

    int port;

    EventLoopGroup boss ;
    EventLoopGroup worker;

    public HttpServer(int port){
        this.port = port;
        boss = new NioEventLoopGroup(1);
        worker = new NioEventLoopGroup();
    }

    public HttpServer(int port,EventLoopGroup boss,EventLoopGroup worker){
        this.port = port;
        this.boss = boss;
        this.worker = worker;
    }

    @Override
    public void run() {
        ChannelFuture future = null;
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(boss, worker);
            serverBootstrap.channel(NioServerSocketChannel.class);
            // 初始化服务端可连接队列
            serverBootstrap.option(ChannelOption.SO_BACKLOG, 1024)
                    // 允许重复使用本地地址和端口，连接关闭后，可以立即重用端口
                    .option(ChannelOption.SO_REUSEADDR, true)
                    // 设置TCP长连接，TCP会主动探测空闲连接的有效性
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    // 禁用Nagle算法，小数据时可以即时传输
                    .childOption(ChannelOption.TCP_NODELAY, true)
                    // 发送缓冲区大小
                    .childOption(ChannelOption.SO_SNDBUF, 256 * 1024)
                    // 接收缓冲区大小
                    .childOption(ChannelOption.SO_RCVBUF, 256 * 1024);
            serverBootstrap.childHandler(new HttpServerInitializer());
            // 绑定端口，开始接收进来的连接
            future = serverBootstrap.bind(port).sync();
            if (future.isSuccess()) {
                log.info("Netty服务端启动!! 端口:[{}]", port);
            }
            future.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            log.error("Netty服务端启动异常!! error:{}", e.getMessage());
        }
    }
}
